import React, { useEffect, useRef, useState } from 'react';

interface UnityConfig {
  dataUrl: string;
  frameworkUrl: string;
  codeUrl: string;
  streamingAssetsUrl: string;
  companyName: string;
  productName: string;
  productVersion: string;
  showBanner: (msg: string, type: string) => void;
}

const UnityCanvas: React.FC = () => {
  const unityContainerRef = useRef<HTMLDivElement>(null);
  const unityCanvasRef = useRef<HTMLCanvasElement>(null);
  const loadingBarRef = useRef<HTMLDivElement>(null);
  const progressBarFullRef = useRef<HTMLDivElement>(null);
  const fullscreenButtonRef = useRef<HTMLDivElement>(null);
  const getAllObjectButtonRef = useRef<HTMLDivElement>(null);
  const warningBannerRef = useRef<HTMLDivElement>(null);
  const [unityInstance, setUnityInstance] = useState<any>(null);

  // 显示临时消息横幅或永久错误消息
  const unityShowBanner = (msg: string, type: string) => {
    const updateBannerVisibility = () => {
      if (warningBannerRef.current) {
        warningBannerRef.current.style.display = warningBannerRef.current.children.length ? 'block' : 'none';
      }
    };
    if (warningBannerRef.current) {
      const div = document.createElement('div');
      div.innerHTML = msg;
      warningBannerRef.current.appendChild(div);
      if (type === 'error') div.style = 'background: red; padding: 10px;';
      else {
        if (type === 'warning') div.style = 'background: yellow; padding: 10px;';
        setTimeout(() => {
          if (warningBannerRef.current) {
            warningBannerRef.current.removeChild(div);
            updateBannerVisibility();
          }
        }, 5000);
      }
      updateBannerVisibility();
    }
  };

  useEffect(() => {
    const buildUrl = "http://localhost:8080/Build";
    const loaderUrl = buildUrl + "/072552122.loader.js";
    const config: UnityConfig = {
      dataUrl: buildUrl + "/072552122.data.gz",
      frameworkUrl: buildUrl + "/072552122.framework.js.gz",
      codeUrl: buildUrl + "/072552122.wasm.gz",
      streamingAssetsUrl: "StreamingAssets",
      companyName: "DefaultCompany",
      productName: "3d-built-in",
      productVersion: "0.1",
      showBanner: unityShowBanner,
    };

    if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
      // 移动设备样式
      const meta = document.createElement('meta');
      meta.name = 'viewport';
      meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
      document.getElementsByTagName('head')[0].appendChild(meta);
      if (unityContainerRef.current) unityContainerRef.current.className = "unity-mobile";
      if (unityCanvasRef.current) unityCanvasRef.current.className = "unity-mobile";
    } else {
      // 桌面端样式
      if (unityCanvasRef.current) {
        unityCanvasRef.current.style.width = "960px";
        unityCanvasRef.current.style.height = "600px";
      }
    }

    if (loadingBarRef.current) loadingBarRef.current.style.display = "block";

    const script = document.createElement("script");
    script.src = loaderUrl;
    script.onload = () => {
      if (unityCanvasRef.current) {
        (window as any).createUnityInstance(unityCanvasRef.current, config, (progress: number) => {
          if (progressBarFullRef.current) {
            progressBarFullRef.current.style.width = 100 * progress + "%";
          }
        }).then((ins: any) => {
          setUnityInstance(ins);
          if (loadingBarRef.current) loadingBarRef.current.style.display = "none";
          if (fullscreenButtonRef.current) {
            fullscreenButtonRef.current.onclick = () => {
              ins.SetFullscreen(1);
            };
          }
          if (getAllObjectButtonRef.current) {
            getAllObjectButtonRef.current.onclick = () => {
              ins.SendMessage("ObjectManager", "GetAllObjectNames");
            };
          }
        }).catch((message: string) => {
          alert(message);
        });
      }
    };

    document.body.appendChild(script);

    // 接收Unity发送的物体名称列表
    (window as any).receiveObjectNames = (objectNamesJson: string) => {
      const objectList = document.createElement('div');
      objectList.style = 'margin-top: 10px; padding: 10px; border: 1px solid #ccc;';
      const wrapper = JSON.parse(objectNamesJson);
      console.log(wrapper);
      const objects = wrapper.objects || [];
      objectList.innerHTML = "<strong>场景物体列表:</strong><br>" + objects.join("<br>");
      document.body.appendChild(objectList);
    };

    // 设置相机变换
    (window as any).setCameraTransform = (position: any, rotation: any, fieldOfView: number) => {
      if (unityInstance) {
        const jsonParams = JSON.stringify({
          position: {
            x: position.x,
            y: position.y,
            z: position.z,
          },
          rotation: {
            x: rotation.x,
            y: rotation.y,
            z: rotation.z,
          },
          fieldOfView: fieldOfView,
        });
        unityInstance.SendMessage("Main Camera", "JS_SetCameraTransform", jsonParams);
      }
    };

    // 测试函数
    (window as any).test = () => {
      (window as any).setCameraTransform({ x: 6.61, y: 2.36, z: -15 }, { x: 0, y: 0, z: 0 }, 60);
    };

    return () => {
      // 清理脚本
      document.body.removeChild(script);
      // 清理全局函数
      delete (window as any).receiveObjectNames;
      delete (window as any).setCameraTransform;
      delete (window as any).test;
    };
  }, [unityInstance]);

  return (
    <>
      <div id="unity-container" className="unity-desktop" ref={unityContainerRef}>
        <canvas id="unity-canvas" width={960} height={600} tabIndex={-1} ref={unityCanvasRef} />
        <div id="unity-loading-bar" ref={loadingBarRef}>
          <div id="unity-logo"></div>
          <div id="unity-progress-bar-empty">
            <div id="unity-progress-bar-full" ref={progressBarFullRef}></div>
          </div>
        </div>
        <div id="unity-warning" ref={warningBannerRef}></div>
        <div id="unity-footer">
          <div id="unity-webgl-logo"></div>
          <div id="unity-fullscreen-button" ref={fullscreenButtonRef}></div>
          <div id="unity-getallobject" ref={getAllObjectButtonRef}>获取所有物体</div>
          <div id="unity-build-title">3d-built-in</div>
        </div>
      </div>
    </>
  );
};

export default UnityCanvas;
